import { useReducer, useCallback } from 'react'

// hooks 必须在函数式组件 和 另一个钩子里使用
// const foo = () => {
//   const [num, setNum] = useState(100)
// }

const defaultState = {
  count: 0
}

const reducer = (state, action) => {
  switch(action.type) {
    case 'add':
      return {
        count: state.count + 1
      }

    case 'minus':
      return {
        count: state.count - 1
      }

    default: 
      return state
  }
}

const Counter = () => {
  // const [count, setCount] = useState(0)
  const [state, dispatch] = useReducer(reducer, defaultState)

  const add = useCallback(
    () => {
      dispatch({
        type: 'add'
      })
    },
    [],
  )

  return (
    <div>{state.count} <button onClick={add}>+</button></div>
  )
}

export default Counter